package com.sq.goodline.service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.sq.goodline.config.ApiConfig;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class SshService {
	
	@Resource
	ApiConfig apiConfig;
	
	/**
	 * ssh登录vos服务器，执行ssh命令
	 * @param shellCmd
	 * @return
	 * @throws Exception
	 */
	public String exeSshRemoteCmd(String shellCmd) throws Exception {
		Connection connect = new Connection(apiConfig.getVosServer(),22);
		InputStream inputStream = null;
		try {
			connect.connect();
	    	if( connect.authenticateWithPassword(apiConfig.getVosServerUser(), apiConfig.getVosServerPwd()) ) {
	    		log.info("登录238成功");
				
				Session session = connect.openSession();
				session.execCommand(shellCmd);//执行命令
				inputStream = session.getStdout();
				
				// 读取命令的输出
		        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
		        StringBuffer sb = new StringBuffer(); 
		        String line;
		        while ((line = reader.readLine()) != null) {
		        	sb.append(line);
		        }
				return sb.toString();
			}else {
				log.info("登录认证失败");
				return null;
			}
    	}finally {
			if (null != inputStream) {
				inputStream.close();
			}
			connect.close();
		}
    }
	
	/**
	 * 将远程服务器文件下载到本地目录
	 * @param remoteFile
	 * @param localTargetDirectory
	 * @throws Exception
	 */
	public void scpGetFile(String remoteFile, String localTargetDirectory) throws Exception {
		Connection connect = new Connection(apiConfig.getVosServer(),22);
		connect.connect();
		try {
	    	if(connect.authenticateWithPassword(apiConfig.getVosServerUser(), apiConfig.getVosServerPwd())) {
	    		log.info("登录238成功");
	    		SCPClient client = new SCPClient(connect);
	    		client.get(remoteFile,localTargetDirectory);
	    	}else {
				log.info("登录认证失败");
			}
		}finally {
			connect.close();
		}
	}
}
